package role

import (
	"fmt"
	"reflect"
	"sanguo/cluster"
	codecs "sanguo/codec/cs"
	"sanguo/node/common/aoi"
	ss_message "sanguo/protocol/ss/message"

	"github.com/golang/protobuf/proto"
	//"sanguo/node/node_map"
)

func (this *Role) SendToClient(msg proto.Message) {
	relayMsg := &ss_message.Relay{
		Users: make([]string, 1)[0:0],
	}
	relayMsg.Users = append(relayMsg.Users, this.UserID)
	relayMsg.MsgType = proto.String(reflect.TypeOf(msg).String())
	bytes, err := encoder.EnCode(codecs.NewMessage(0, msg))
	if nil == err {
		//copy(relayMsg.Msg, bytes.Bytes())
		relayMsg.Msg = bytes.Bytes()
		cluster.PostMessage(this.Game, relayMsg)
	} else {
		fmt.Println(err, relayMsg.GetMsgType())
	}
}

func SendMsgToClients(game cluster.PeerID, users []string, msgType string, msg []byte, count int) {
	relayMsg := &ss_message.Relay{
		Users: make([]string, count)[0:0],
	}
	relayMsg.MsgType = proto.String(msgType)
	//copy(relayMsg.Msg, msg)
	relayMsg.Msg = msg
	for _, u := range users {
		relayMsg.Users = append(relayMsg.Users, u)
		if len(relayMsg.Users) == count {
			cluster.PostMessage(game, relayMsg)
			relayMsg.Users = relayMsg.Users[0:0]
		}
	}

	if len(relayMsg.Users) > 0 {
		cluster.PostMessage(game, relayMsg)
	}
}

//将自己的最新状态发送给观察者(包括自己)
func (this *Role) SendViewObjToClient(msgType string, msg []byte) {

	m := map[cluster.PeerID][]string{}
	this.ForEachObserver(func(o_ aoi.AOIObject) {
		o := o_.(*Role)
		v, ok := m[o.Game]
		if !ok {
			v = make([]string, 100)[0:0]
		}
		m[o.Game] = append(v, o.UserID)
	})

	for k, v := range m {
		SendMsgToClients(k, v, msgType, msg, 200)
	}
}
